package mem

import (
	"io"
	"reflect"
	"runtime"
	"unsafe"
)

// 定义泛型的初值
func ZeroValue[T any]() T {
	var r T
	return r
}

// 取切片底层数组地址
func SliceDataAddr[T any](s []T) uintptr {
	return (*reflect.SliceHeader)(unsafe.Pointer(&s)).Data
}

func MakeSlice[T any](v T, n int, cap ...int) []T {
	var r []T
	if len(cap) > 0 {
		r = make([]T, n, cap[0])
	} else {
		r = make([]T, n)
	}
	if n > 0 {
		r[0] = v
		i := 1
		for i < n {
			i += copy(r[i:], r[:i])
		}
	}
	return r
}

// 自动关闭
func AutoClose[T io.Closer](a T) {
	runtime.SetFinalizer(a, func(a T) { a.Close() })
}
